#!/usr/bin/env python
#-*- coding: utf-8 -*-
import requests,time,hashlib
import cookielib,os
import urllib2,urllib
'''
首次登录后,保存cookie文件,用于以后cookie登录验证
'''
def login():
    user = 'admin'
    pwd = '123456'
    data={"username":user,"password":pwd}  #登陆用户名和密码
    post_data=urllib.urlencode(data)   #将post消息化成可以让服务器编码的方式
    ckjar = cookielib.MozillaCookieJar('/tmp/.cookie')
    opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(ckjar))
    #自己设置User-Agent（可用于伪造获取，防止某些网站防ip注入）
    headers ={"User-agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"}
    website = 'http://192.168.137.20:8080/accounts/login/?next=/hostinfo/'
    req=urllib2.Request(website,post_data,headers)
    content=opener.open(req)
    htm = content.read()
    content.close
    ckjar.save(ignore_discard=True, ignore_expires=True)
if __name__ == '__main__':
    key = 'a$#ERsdf@!sdFEf%KDdalep;aidzke.,'
    url ="http://192.168.137.20:8080/hostinfo/getjson"
    timestamp = time.time()
    temp = '{key}|{time}'.format(key=key,time=timestamp)
    md5_str = hashlib.sha256(temp.encode('utf-8')).hexdigest()
    token = '{md5_str}|{time}'.format(md5_str=md5_str, time=timestamp)
    if not os.path.exists('/tmp/.cookie'):
        login()
    cookie=cookielib.MozillaCookieJar()
    cookie.load('/tmp/.cookie',ignore_expires=True,ignore_discard=True)
    req=urllib2.Request(url,headers={"auth-key": token})
    opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
    urllib2.install_opener(opener)
    response=urllib2.urlopen(req)
    print (response.read().decode('utf-8'))
